<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>钱包绑定示例</title>
    <!-- 使用本地 ethers 库，确保运行 `npm install` 后执行 scripts/copy-ethers.js 将库复制到 app/public/libs/ethers.min.js -->
    <script src="/public/libs/ethers.min.js"></script>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        margin: 24px;
      }
      .box {
        max-width: 720px;
        margin: 0 auto;
      }
      label {
        display: block;
        margin-top: 12px;
      }
      button {
        margin-top: 12px;
        padding: 8px 12px;
      }
      pre {
        background: #f6f8fa;
        padding: 12px;
        border-radius: 6px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <h1>钱包绑定演示</h1>

      <p>
        说明：先登录并把后端返回的 JWT 填到
        <code>JWT token</code> 输入框，然后点击“获取 Nonce”，使用 MetaMask
        签名，再提交绑定。
      </p>

      <label>JWT token</label>
      <input
        id="token"
        type="text"
        style="width: 100%"
        placeholder="从 /api/auth/login 返回的 token"
      />

      <label>Nonce</label>
      <pre id="nonce">未获取</pre>
      <button id="btn-get-nonce">获取 Nonce (/api/auth/wallet-nonce)</button>

      <label>钱包地址</label>
      <input id="address" type="text" style="width: 100%" placeholder="0x..." />

      <label>签名（由钱包生成）</label>
      <pre id="signature">未签名</pre>

      <div>
        <button id="btn-connect">连接钱包（MetaMask）</button>
        <button id="btn-sign">用钱包签名 Nonce</button>
        <button id="btn-verify">提交验证(/api/auth/verify-wallet)</button>
      </div>

      <h3>响应</h3>
      <pre id="result">尚无响应</pre>
    </div>

    <script>
      const $ = (id) => document.getElementById(id);
      let provider = null;
      let signer = null;

      async function connectWallet() {
        if (!window.ethereum) return alert("请安装 MetaMask 或兼容的钱包扩展");
        provider = new ethers.providers.Web3Provider(window.ethereum);
        await provider.send("eth_requestAccounts", []);
        signer = provider.getSigner();
        const addr = await signer.getAddress();
        $("address").value = addr;
      }

      async function getNonce() {
        const token = $("token").value.trim();
        if (!token) return alert("请先填写 JWT token");

        const resp = await fetch("/api/auth/wallet-nonce", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + token,
          },
        });
        const data = await resp.json();
        if (data && data.success) {
          $("nonce").textContent = data.data.nonce;
          $("result").textContent = JSON.stringify(data, null, 2);
        } else {
          $("result").textContent = JSON.stringify(data, null, 2);
        }
      }

      async function signNonce() {
        if (!signer) return alert("请先连接钱包");
        const nonce = $("nonce").textContent;
        if (!nonce || nonce === "未获取") return alert("请先获取 nonce");
        const sig = await signer.signMessage(nonce);
        $("signature").textContent = sig;
      }

      async function verifyWallet() {
        const token = $("token").value.trim();
        if (!token) return alert("请先填写 JWT token");
        const address = $("address").value.trim();
        const message = $("nonce").textContent;
        const signature = $("signature").textContent;
        if (!address || !message || !signature)
          return alert("请先连接钱包、获取 nonce 并签名");

        const resp = await fetch("/api/auth/verify-wallet", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + token,
          },
          body: JSON.stringify({ address, message, signature }),
        });
        const data = await resp.json();
        $("result").textContent = JSON.stringify(data, null, 2);
      }

      $("btn-connect").addEventListener("click", connectWallet);
      $("btn-get-nonce").addEventListener("click", getNonce);
      $("btn-sign").addEventListener("click", signNonce);
      $("btn-verify").addEventListener("click", verifyWallet);
    </script>
  </body>
</html>
